import Axios from '@/utils/axios.ts';
import '../../public/marvinjs/js/webservices.js';
import { Constant } from '@/constant';

export class FormulaService {
    private static MARVINJS_SERVICES = (() => {
        const defaultServices = window['MarvinJSServices']();
        let services = {};
        services['molconvertws'] = defaultServices['molconvertws'];
        return services;
    })();

    private static SERVICE: string = FormulaService.MARVINJS_SERVICES['molconvertws'];

    static async convert(inputFormat: string, outputFormat: string, structure: string): Promise<string> {
        var data = {
            structure: structure,
            inputFormat: inputFormat,
            parameters: outputFormat
        };
        const resp = await Axios.post(FormulaService.SERVICE, data);
        return resp.structure;
    }

    static async toImage(marvin, inputFormat: string, structure: string, width: number = Constant.MOLECULE_SIZE, height: number = Constant.MOLECULE_SIZE): Promise<string> {
        var settings = {
            width: width,
            height: height
        };
        var params = {
            imageType: 'image/svg',
            inputFormat: inputFormat,
            services: FormulaService.MARVINJS_SERVICES,
            settings: settings
        };
        return await new marvin.ImageExporter(params).render(structure);
    }

    static getSourceReactants(formula: string): string[] {
        return formula.split('>>')[0].split('.');
    }

    static getUnduplicatedSourceReactants(formula: string): string[] {
        return FormulaService.getSourceReactants(formula).filter((value, index, array) => {
            return array.indexOf(value) >= index;
        });
    }

    static getTargetMolecule(formula: string): string {
        return formula.split('>>')[1];
    }
}
